﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Timers;
using System.Windows;
using System.Windows.Threading;
using HtmlAgilityPack;

namespace _4chanManager.Logic
{
    public class FileDownloader
    {
        private WebClient _webClient;
        private readonly string _folder;
        private readonly string _webAddress;
        private readonly string _extensions;
        public int RefreshTreadEvery;
        private readonly List<string> _linksAlreadyDownloaded;
        private Timer dt;
        public event Helpers.ThreadStatusDelegate StatusChanged;
        private volatile bool _isDownloading;

        public FileDownloader(string webAddress , string extensions, string folder)
        {
            _webAddress = webAddress;
            _extensions = extensions;
            _folder = folder;
            _linksAlreadyDownloaded = new List<string>();
            
        }

        private void GetFile(string adress)
        {
            _isDownloading = true;
            if (string.IsNullOrEmpty(_folder) || string.IsNullOrEmpty(adress))
                return;
            try
            {
                using (_webClient = new WebClient())
                {
                    _webClient.Headers.Add("user-agent", Helpers.UserAgentHeader);
                    string html = _webClient.DownloadString(adress);
                    HtmlDocument doc = new HtmlDocument();
                    doc.LoadHtml(html);
                    FireStatusChanged(true);
                    var hrefList = doc.DocumentNode.SelectNodes("//a")
                        .Select(p => p.GetAttributeValue("href", "not found"))
                        .ToList();
                    List<string> goodLinks = new List<string>();
                    foreach (var ext in _extensions.Split(' '))
                    {
                        goodLinks.AddRange(hrefList.Where(a => a.EndsWith(ext)));
                    }
                    foreach (var link in goodLinks)
                    {
                        string newFile = Helpers.CreateNewFilePath(_folder, link.Split('/').Last(), string.Empty);
                        if (_linksAlreadyDownloaded.Contains(link) || File.Exists(newFile)) continue;

                        _linksAlreadyDownloaded.Add(link);
                        _webClient.DownloadFile("http:" + link, newFile);
                    }
                }
            }
            catch (Exception e)
            {
                FireStatusChanged(false);
                MessageBox.Show("Somethning went wrong : " + e);
                if (dt != null)
                    dt.Stop();
            }
            finally
            {
                _isDownloading = false;
            }

        }



        public void Start()
        {
            if (RefreshTreadEvery > 0)
            {
                dt = new Timer(RefreshTreadEvery*60*1000);
                dt.Elapsed += dt_Tick;
                dt.Start();
            }
            GetFile(_webAddress);
        }

        void FireStatusChanged(bool? value)
        {
            if (StatusChanged != null)
                StatusChanged(value);
             
        }

        void dt_Tick(object sender, EventArgs e)
        {
            if(!_isDownloading)
                GetFile(_webAddress);
        }

        
    }
}

